use fluviox_smart_modules::{
    registry::{SmartModuleRegistry, get_global_registry},
    traits::{SmartModuleFactory, SmartModule, SmartModuleType},
    transforms::{FieldMapper, JsonTransformer},
    filters::{ConditionFilter},
    engine::SmartModuleEngine,
    SmartModuleConfig,
};
use fluviox_shared::models::DataRecord;
use serde_json::{json, Value};
use std::collections::HashMap;
use uuid::Uuid;
use chrono::Utc;

#[test]
fn test_smart_module_registry() {
    let registry = SmartModuleRegistry::new();
    
    // 测试支持的模块列表
    let modules = registry.list_modules();
    assert!(modules.contains(&"field-mapper".to_string()));
    assert!(modules.contains(&"json-transformer".to_string()));
    assert!(modules.contains(&"condition-filter".to_string()));
    
    println!("✅ SmartModule注册表测试通过");
}

#[test]
fn test_module_creation() {
    let registry = SmartModuleRegistry::new();
    
    // 测试创建字段映射器
    let field_mapper = registry.create_module("field-mapper");
    assert!(field_mapper.is_ok());
    
    // 测试创建JSON转换器
    let json_transformer = registry.create_module("json-transformer");
    assert!(json_transformer.is_ok());
    
    // 测试创建条件过滤器
    let condition_filter = registry.create_module("condition-filter");
    assert!(condition_filter.is_ok());
    
    // 测试创建不存在的模块
    let unknown_module = registry.create_module("unknown");
    assert!(unknown_module.is_err());
    
    println!("✅ 模块创建测试通过");
}

#[test]
fn test_global_registry() {
    let registry = get_global_registry();
    
    let modules = registry.list_modules();
    assert!(!modules.is_empty());
    
    let metadata = registry.supported_modules();
    assert!(!metadata.is_empty());
    
    println!("✅ 全局注册表测试通过");
}

#[test]
fn test_module_metadata() {
    let registry = SmartModuleRegistry::new();
    
    let metadata = registry.supported_modules();
    assert!(!metadata.is_empty());
    
    // 验证字段映射器元数据
    let field_mapper_meta = metadata.iter()
        .find(|m| m.name == "field-mapper")
        .expect("应该找到字段映射器元数据");
    
    assert_eq!(field_mapper_meta.version, "1.0.0");
    assert_eq!(field_mapper_meta.module_type, SmartModuleType::Transform);
    assert!(!field_mapper_meta.description.is_empty());
    assert!(!field_mapper_meta.config_schema.is_null());
    
    println!("✅ 模块元数据测试通过");
}

#[tokio::test]
async fn test_field_mapper() {
    let mut field_mapper = FieldMapper::new();
    
    // 测试模块基本信息
    assert_eq!(field_mapper.name(), "field-mapper");
    assert_eq!(field_mapper.version(), "1.0.0");
    assert_eq!(field_mapper.module_type(), SmartModuleType::Transform);
    
    // 配置字段映射
    let config = json!({
        "field_mappings": {
            "old_name": "new_name",
            "user_id": "id"
        },
        "fields_to_remove": ["temp_field"],
        "fields_to_add": {
            "processed": true
        },
        "keep_unmapped": true
    });
    
    // 初始化模块
    let init_result = field_mapper.initialize(config).await;
    assert!(init_result.is_ok());
    
    // 创建测试记录
    let test_data = json!({
        "old_name": "test",
        "user_id": 123,
        "temp_field": "remove_me",
        "keep_me": "value"
    });
    
    let record = DataRecord {
        id: Uuid::new_v4(),
        topic: "test".to_string(),
        partition: 0,
        offset: 0,
        timestamp: Utc::now(),
        data: test_data,
        metadata: HashMap::new(),
    };
    
    // 处理记录
    let results = field_mapper.process(record).await;
    assert!(results.is_ok());
    
    let processed_results = results.unwrap();
    assert_eq!(processed_results.len(), 1);
    
    if let Some(result) = processed_results.first() {
        match result {
            fluviox_smart_modules::ProcessResult::Transform(transformed_record) => {
                let data = &transformed_record.data;
                
                // 验证字段重命名
                assert!(data.get("new_name").is_some());
                assert!(data.get("id").is_some());
                assert!(data.get("old_name").is_none());
                assert!(data.get("user_id").is_none());
                
                // 验证字段删除
                assert!(data.get("temp_field").is_none());
                
                // 验证字段添加
                assert_eq!(data.get("processed"), Some(&json!(true)));
                
                // 验证保留未映射字段
                assert!(data.get("keep_me").is_some());
            },
            _ => panic!("期望Transform结果"),
        }
    }
    
    println!("✅ 字段映射器测试通过");
}

#[tokio::test]
async fn test_json_transformer() {
    let mut json_transformer = JsonTransformer::new();
    
    // 配置JSON转换器
    let config = json!({
        "extractions": [
            {
                "source_path": "$.user.name",
                "target_field": "username",
                "required": true
            },
            {
                "source_path": "$.user.age",
                "target_field": "user_age",
                "required": false,
                "default_value": 0
            }
        ],
        "flatten": false,
        "remove_null": true,
        "output_mode": "merge"
    });
    
    // 初始化模块
    let init_result = json_transformer.initialize(config).await;
    assert!(init_result.is_ok());
    
    // 创建测试记录
    let test_data = json!({
        "user": {
            "name": "Alice",
            "age": 25
        },
        "event": "login",
        "null_field": null
    });
    
    let record = DataRecord {
        id: Uuid::new_v4(),
        topic: "test".to_string(),
        partition: 0,
        offset: 0,
        timestamp: Utc::now(),
        data: test_data,
        metadata: HashMap::new(),
    };
    
    // 处理记录
    let results = json_transformer.process(record).await;
    assert!(results.is_ok());
    
    let processed_results = results.unwrap();
    assert_eq!(processed_results.len(), 1);
    
    if let Some(result) = processed_results.first() {
        match result {
            fluviox_smart_modules::ProcessResult::Transform(transformed_record) => {
                let data = &transformed_record.data;
                
                // 验证JSONPath提取
                assert_eq!(data.get("username"), Some(&json!("Alice")));
                assert_eq!(data.get("user_age"), Some(&json!(25)));
                
                // 验证原始数据保留（merge模式）
                assert!(data.get("event").is_some());
                
                // 验证空值移除
                assert!(data.get("null_field").is_none());
            },
            _ => panic!("期望Transform结果"),
        }
    }
    
    println!("✅ JSON转换器测试通过");
}

#[tokio::test]
async fn test_condition_filter() {
    let mut condition_filter = ConditionFilter::new();
    
    // 配置条件过滤器
    let config = json!({
        "conditions": [
            {
                "field_path": "status",
                "operator": "eq",
                "value": "active"
            },
            {
                "field_path": "user.age",
                "operator": "gte",
                "value": 18
            }
        ],
        "logic": "and"
    });
    
    // 初始化模块
    let init_result = condition_filter.initialize(config).await;
    assert!(init_result.is_ok());
    
    // 创建测试记录（应该通过过滤）
    let test_data_pass = json!({
        "status": "active",
        "user": {
            "age": 25,
            "name": "Alice"
        }
    });
    
    let record_pass = DataRecord {
        id: Uuid::new_v4(),
        topic: "test".to_string(),
        partition: 0,
        offset: 0,
        timestamp: Utc::now(),
        data: test_data_pass,
        metadata: HashMap::new(),
    };
    
    // 处理记录（应该通过）
    let results_pass = condition_filter.process(record_pass).await;
    assert!(results_pass.is_ok());
    
    let processed_results_pass = results_pass.unwrap();
    assert_eq!(processed_results_pass.len(), 1);
    assert!(matches!(processed_results_pass[0], fluviox_smart_modules::ProcessResult::Keep(_)));
    
    // 创建测试记录（应该被过滤）
    let test_data_filter = json!({
        "status": "inactive",
        "user": {
            "age": 16,
            "name": "Bob"
        }
    });
    
    let record_filter = DataRecord {
        id: Uuid::new_v4(),
        topic: "test".to_string(),
        partition: 0,
        offset: 0,
        timestamp: Utc::now(),
        data: test_data_filter,
        metadata: HashMap::new(),
    };
    
    // 处理记录（应该被过滤）
    let results_filter = condition_filter.process(record_filter).await;
    assert!(results_filter.is_ok());
    
    let processed_results_filter = results_filter.unwrap();
    assert_eq!(processed_results_filter.len(), 1);
    assert!(matches!(processed_results_filter[0], fluviox_smart_modules::ProcessResult::Filter));
    
    println!("✅ 条件过滤器测试通过");
}

#[tokio::test]
async fn test_smart_module_engine() {
    let mut engine = SmartModuleEngine::new();
    
    // 添加字段映射器
    let field_mapper_config = SmartModuleConfig {
        name: "field-mapper".to_string(),
        module_type: SmartModuleType::Transform,
        parameters: {
            let mut params = HashMap::new();
            params.insert("field_mappings".to_string(), json!({"old_name": "new_name"}));
            params.insert("keep_unmapped".to_string(), json!(true));
            params
        },
        enabled: true,
        order: 1,
    };
    
    let add_result = engine.add_module(field_mapper_config).await;
    assert!(add_result.is_ok());
    
    // 添加条件过滤器
    let filter_config = SmartModuleConfig {
        name: "condition-filter".to_string(),
        module_type: SmartModuleType::Filter,
        parameters: {
            let mut params = HashMap::new();
            params.insert("conditions".to_string(), json!([
                {
                    "field_path": "new_name",
                    "operator": "eq",
                    "value": "test"
                }
            ]));
            params.insert("logic".to_string(), json!("and"));
            params
        },
        enabled: true,
        order: 2,
    };
    
    let add_filter_result = engine.add_module(filter_config).await;
    assert!(add_filter_result.is_ok());
    
    assert_eq!(engine.module_count(), 2);
    
    // 创建测试记录
    let test_data = json!({
        "old_name": "test",
        "other_field": "value"
    });
    
    let record = DataRecord {
        id: Uuid::new_v4(),
        topic: "test".to_string(),
        partition: 0,
        offset: 0,
        timestamp: Utc::now(),
        data: test_data,
        metadata: HashMap::new(),
    };
    
    // 处理记录
    let results = engine.process_record(record).await;
    assert!(results.is_ok());
    
    let processed_results = results.unwrap();
    assert_eq!(processed_results.len(), 1);
    
    // 验证处理结果
    let result_record = &processed_results[0];
    assert!(result_record.data.get("new_name").is_some());
    assert!(result_record.data.get("old_name").is_none());
    
    println!("✅ SmartModule引擎测试通过");
}
